<script>
  import {systemParameter} from "../../api/systemParameter";
  import {mapGetters} from 'vuex'

  export default {
    name: 'BaseChat',
    created() {
      this.initConectWebSocket(50001)
    },
    computed: {
      ...mapGetters([
        'userInfo',
        'role'
      ])
    },
    destroyed() {
      this.websock = null
    },
    data() {
      return {
        url: '',
        websock: null,
        sendData:{
          clientId:null,
          content:null,
        },
        onMessage:null,
      }
    },
    methods: {
      /**
       * 初始化连接
       */
      initConectWebSocket(type) {
        systemParameter({systemType: type}).then(response => {
          this.url = response.data[50000][0].systemValue+'/'+this.userInfo.pkClientId;
          this.initWebSocket(this.url);
        });
      },

      /**
       * 打开链接
       * @param url
       */
      initWebSocket(url) {
        this.websock = new WebSocket(url);
        this.websock.onerror = this.webSocketOnError;
        this.websock.onopen = this.websocketonopen;
        this.websock.onmessage = this.webSocketOnMessage;
        this.websock.onclose = this.webSocketClose;
      },


      /**
       *  打开链接
       */
      websocketonopen() {
        console.warn('webSocket 连接成功！')
      },


      /**
       * 发送消息
       * @param Mesage
       */
      webSocketOnSend(Mesage) {
        this.websock.send(JSON.stringify(Mesage));
      },

      /**
       * socket 错误
       * @param e
       */
      webSocketOnError(e) {

      },


      /**
       * 接收消息
       * @param e
       */
      webSocketOnMessage(e) {
        this.onMessage = JSON.parse(e.data)
        console.log('sss = ',this.onMessage);
      },


      /**
       * 关闭
       * @param e
       */
      webSocketClose(e) {
        this.initWebSocket(this.url);
      },
    }
  }
</script>

<style>

</style>
